package com.hsy.leancloudchat.main

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import cn.leancloud.LCUser
import cn.leancloud.im.v2.LCIMClient
import cn.leancloud.im.v2.LCIMConversation
import cn.leancloud.im.v2.LCIMMessage
import com.hsy.leancloudchat.CustomIMEventHandler
import com.hsy.leancloudchat.LeanCloudHelper
import com.hsy.leancloudchat.databinding.ActivityMainBinding
import com.hsy.leancloudchat.login.LoginActivity
import com.hsy.leancloudchat.mvvmUtils.HsyActivity

class MainActivity : HsyActivity<ActivityMainBinding, MainViewModel>(),
    CustomIMEventHandler.IIMEventSubscriber {
    private var mRequestConversationList = mutableListOf<LCIMConversation>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        CustomIMEventHandler.subscribe(this)

        initRVConversationExist()
        setButtonsClick()
        setTopAddInputBar()

        initInfo()

        mViewModel.mRequestConversationListLiveData.observe(this) {
            mRequestConversationList = it
            if (it.size != 0) {
                mBinding.tipRequest.apply {
                    visibility = View.VISIBLE
                    text = it.size.toString()
                }
            }
        }

        mViewModel.mExistConversationListLiveData.observe(this) {
            Log.v("hsy111", "mExistConversationListLiveData.size -> ${it.size}")
            (mBinding.rvExitConversation.adapter as ConversationExistAdapter)
                .conversationExistList = it
        }
    }

    override fun onResume() {
        super.onResume()
        queryConversation()
    }

    override fun onDestroy() {
        super.onDestroy()
        CustomIMEventHandler.unSubscribe(this)
    }

    override fun onInvited(
        client: LCIMClient?,
        conversation: LCIMConversation?,
        operator: String?
    ) {
        queryConversation()
    }

    override fun onMessage(
        message: LCIMMessage?,
        conversation: LCIMConversation?,
        client: LCIMClient?
    ) {
        // todo --- 遍历 conversationList更新，要不然这样太浪费 api了
        queryConversation()
    }

    private fun initInfo() {
        mBinding.topMyName.text = LCUser.currentUser().username
        mBinding.topObjectId.text = LCUser.currentUser().objectId

        mBinding.topObjectId.setOnClickListener {
            val clipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
            val text = (it as TextView).text.toString().trim()
            val clip = ClipData.newPlainText("text", text)
            clipboard.setPrimaryClip(clip)

            Toast.makeText(this, "已复制到剪贴板", Toast.LENGTH_SHORT).show()
        }
    }

    @SuppressLint("CheckResult")
    private fun setTopAddInputBar() {
        mBinding.btSend.setOnClickListener {
            val editText = mBinding.etInput
            if (editText.text.toString() == "") return@setOnClickListener
            if (editText.text.toString() == LCUser.currentUser().objectId) {
                Toast(this).apply {
                    setText("加自己干啥")
                    show()
                }
                editText.setText("")
                return@setOnClickListener
            }
            val foundUserLiveData = MutableLiveData<LCUser?>()
            LeanCloudHelper.getInstance().getUserInBackGround(
                editText.text.toString(),
                foundUserLiveData
            )
            foundUserLiveData.observe(this) {
                Log.v("hsy111", foundUserLiveData.value.toString())
                if (it != null) {
                    LeanCloudHelper.getInstance().createConversation(
                        LeanCloudHelper.mCurrentClientLiveData.value!!,
                        mutableListOf(editText.text.toString()),
                        LCUser.currentUser().username!! + " & " + it.username,
                        this
                    ) {
                        Toast(this).apply {
                            setText("好友请求已发送")
                            show()
                        }
                    }
                    editText.setText("")
                } else {
                    Toast(this).apply {
                        setText("用户不存在")
                        show()
                    }
                }
            }
        }
    }

    private fun initRVConversationExist() {
        mBinding.rvExitConversation.apply {
            adapter = ConversationExistAdapter(this@MainActivity)
            layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
        }
    }

    private fun setButtonsClick() {
        mBinding.btnConversationRequest.setOnClickListener {
            ConversationRequestBottomDialog(this).apply {
                show()
                setItemList(mRequestConversationList)
                setOnDismissListener {
                    queryConversation()
                }
                setAcceptListener {
                    if (it == 0) {
                        mBinding.tipRequest.visibility = View.INVISIBLE
                    }
                }
            }
        }
        mBinding.btnExit.setOnClickListener {
            startActivity(Intent(this, LoginActivity::class.java))
            finish()
        }
    }

    private fun queryConversation() {
        // 查询相关对话
        LeanCloudHelper.mCurrentClientLiveData.observe(this) {
            LeanCloudHelper.getInstance().queryConversationContainCurrentClient(
                it,
                mViewModel.mRequestConversationListLiveData,
                mViewModel.mExistConversationListLiveData
            )
        }
    }
}